package com.yunyun400.vosk.controller;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.yunyun400.vosk.service.SpeechService;
import com.yunyun400.vosk.util.Language;

@RestController
@RequestMapping("/api/speech")
public class SpeechController {

    @Autowired
    private SpeechService speechService;

    @PostMapping("/transcribe")
    public ResponseEntity transcribe(@RequestParam("file") MultipartFile file,@RequestParam(value = "language", defaultValue = "th") String languageCode) throws IOException, UnsupportedAudioFileException, LineUnavailableException {
    	if (file.isEmpty()) {
            return ResponseEntity.badRequest().body("请上传一个文件。");
        }

        if (!file.getContentType().equals("audio/mpeg")) {
            return ResponseEntity.badRequest().body("请上传 MP3 格式的音频文件。");
        }
        
        // 根据传入的语言代码字符串，获取对应的 Language 枚举
        Language language = Language.fromCode(languageCode);
        if (language == null) {
            return ResponseEntity.badRequest().body("不支持的语言代码: " + languageCode + "。当前支持的语言有: cn (中文), th (泰语), en(英语)");
        }

        try {
            // 创建临时文件用于存储上传的MP3
            Path tempDir = Files.createTempDirectory("controller-temp-");
            File tempFile = new File(tempDir.toFile(), "uploaded.mp3");
            
            try {
                // 将MultipartFile保存为临时File
                file.transferTo(tempFile);
                System.out.println("上传文件已转换为临时文件: " + tempFile.getAbsolutePath());
                
                // 调用新的service方法，使用File类型参数
                String recognitionResult = speechService.recognizeSpeechFromFile(tempFile, language);
                System.out.println(recognitionResult);
                return ResponseEntity.ok(recognitionResult);
            } finally {
                // 确保临时文件被删除
                Files.deleteIfExists(tempFile.toPath());
                Files.deleteIfExists(tempDir);
                System.out.println("控制器临时文件已清理");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.internalServerError().body("语音识别失败: " + e.getMessage());
        }
    }
}